﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Net.Mime;

namespace GestionDeCinebox.Classes
{
    public class ImageProcessor
    {
        public ImageProcessor()
        {

        }

        /// <summary>
        /// Load image from database
        /// </summary>
        /// <param name="id">Id of film</param>
        /// <returns>Link to image loaded</returns>
        public String LoadImage(String id)
        {
            String conString = "Data Source=DYNG09-PC\\SQLEXPRESS;Initial Catalog=QLRAPPHIM;Integrated Security=True";
            SqlConnection con;
            con = new SqlConnection(conString);
            con.Open();

            String q = "select * from Films where IDFilm='" + id + "'";
            SqlDataAdapter ad = new SqlDataAdapter(q, con);
            DataSet ds = new DataSet();
            ad.Fill(ds);
            String fileName = "";
            if (ds.Tables[0].Rows.Count == 1)
            {
                Byte[] data = new Byte[0];
                data = (Byte[])(ds.Tables[0].Rows[0]["Image"]);
                MemoryStream mem = new MemoryStream(data);
                Image image = Image.FromStream(mem);
                string strfolder = "C:\\Temps";
                if (!Directory.Exists(strfolder))
                {
                    Directory.CreateDirectory(strfolder);
                }
                fileName = "C:\\Temps\\result" + id + ".jpg";
                if (!File.Exists(fileName))
                {
                    image.Save(fileName, ImageFormat.Jpeg);
                }
            }

            return fileName;
        }

        /// <summary>
        /// Insert image into database
        /// </summary>
        /// <param name="id"></param>
        /// <param name="path"></param>
        public void InsertImage(String id, String path)
        {
            String conString = "Data Source=DYNG09-PC\\SQLEXPRESS;Initial Catalog=QLRAPPHIM;Integrated Security=True";
            SqlConnection con;
            con = new SqlConnection(conString);
            con.Open();

            byte[] image = File.ReadAllBytes(path);

            string result = "";
            SqlCommand updateCmd = new SqlCommand("sp_UpdateHinhPhim", con);
            updateCmd.CommandType = CommandType.StoredProcedure;
            updateCmd.Parameters.Add("@image", SqlDbType.Image).Value = image;
            updateCmd.Parameters.Add("@id", SqlDbType.Char).Value = id;
            updateCmd.Parameters.Add("@result", SqlDbType.NVarChar).Value = result;
            updateCmd.ExecuteNonQuery();
        }
    }
}
